<template>
  <view>
    <view class="input-search">
    	<uni-easyinput prefixIcon="search"  trim="all" v-model="keyword" :styles="styles" :placeholderStyle="placeholderStyle"></uni-easyinput>
		<button @click="search">搜索</button>
    </view>
    
    <!-- stripe type="selection" 开启多选 -->
    <uni-table ref="table" type="selection" :loading="loading" emptyText="暂无更多数据" filter-type="search"  @selection-change="selectionChange">
	  <uni-tr>
		<uni-th>
			<button class="close_btn del_btn" @click="toDelete">删除</button>
			<button class="close_btn ok_btn" @click="toOk">确认完成</button>
			<!-- <button class="close_btn" @click="toSyn">同步</button> -->
			<button class="close_btn" @click="toUnSyn">撤销同步</button>
			
			<!-- <text class="th-tip-text">左滑查看明细</text> -->
		</uni-th>
	</uni-tr>
        <uni-tr v-for="(item, index) in card_arr" :key="index" >
			<uni-swipe-action >
			<uni-swipe-action-item :right-options="right_options" show="none"
			 :auto-close="false" @click="selectes(item,'detail')">
			<uni-td style="width:100vw" align="left" class="td-class">
				<div @click="selectes(item,'toscan')" @longpress="longPressDelete(index)" class="td_div">
					<!-- <progress :percent="item.rat" show-info stroke-width="15" activeColor="#18bc9c" backgroundColor="#999" /> -->
					<view class="td_list">
						<text class="label">调拨单号：</text>
						<text class="text font-red">{{ item.FBillNo }}</text>
					</view>
					<view class="td_list">
						<text class="label">单据日期：</text>
						<text class="text">{{ item.FDate }}</text>
					</view>
					<view class="td_list" v-show="item.type==2?true:false">
						<text class="label">编码区间：</text>
						<text class="text">{{ item.invStart }} - {{item.invEnd}}</text>
					</view>
					<view class="td_list" v-show="item.stock_id!=item.to_stock_id?true:false">
						<text class="label">原仓库：</text>
						<text class="text">{{ $Func.getStockNameByStockID(item.stock_id) }}</text>
					</view>
					<view class="td_list" v-show="item.stock_id==item.to_stock_id?true:false">
						<text class="label">所在仓库：</text>
						<text class="text">{{ $Func.getStockNameByStockID(item.stock_id) }}</text>
					</view>
					<view class="td_list" > <!-- v-show="item.stock_id!=item.to_stock_id?true:false" -->
						<text class="label">目标仓库：</text>
						<text class="text">{{ $Func.getStockNameByStockID(item.to_stock_id) }}</text>
					</view>
					<view class="td_list">
						<text class="label">目标库区：</text>
						<text class="text">{{ item.to_shelves_name }}</text>
					</view>
					<view class="td_list">
						<text class="label">摘要：</text>
						<text class="text">{{ item.remark }}</text>
					</view>
					<view class="td_list">
						<text class="label">总数：</text>
						<text class="text">{{ $Func.decimalPattern(item.totalnum) }}</text>
					</view>
					<view class="td_list">
						<text class="label">调拨状态：</text>
						<text class="text">{{ item.status==1? "已完成" : "未完成"  }}</text>
					</view>
					<view class="td_list">
						<text class="label">同步状态：</text>
						<text class="text">{{ item.syn_status==1? "已同步" : "未同步"  }}</text>
					</view>
				</div>
			</uni-td>
			</uni-swipe-action-item>
			</uni-swipe-action>
        </uni-tr>
    </uni-table>
	
    <view class="uni-pagination-box">
		<uni-pagination show-icon :page-size="pageSize" :current="currentPage"
        :total="total" @change="change" />
	</view>
	
	<uni-popup ref="popup" :animation="true" type="center" :maskClick="true">
		<view class="popup-content">
			<view class="pupup-search">
				<view class="center">1、按住调拨记录右滑查看明细</view>
			</view>
			<view class="pupup-search">
				<view class="center">2、点击调拨记录进入扫描页面</view>
			</view>
			<view class="pupup-search">
				<view class="center">3、确认完成传回WMS平台</view>
			</view>
		</view>
	</uni-popup>
  </view>
</template>

<script>
// 引入uni-ui组件
import {
  uniPagination,
  uniTable,
  uniTr,
  uniTh,
  uniTd,
  uniEasyinput,
  uniSwipeActionItem,uniPopup
} from "@dcloudio/uni-ui"
export default {
	components: {
	  uniPagination,
	  uniTable,
	  uniTr,
	  uniTh,
	  uniTd,
	  uniEasyinput,
	  uniSwipeActionItem,uniPopup
	},
  data() {
    return {
      card_arr: [],//当前页码的表格数据
      pageSize: 15,// 每页数据量
      currentPage: 1,// 当前页
      total: 0,// 数据总量
      loading: false,
	  placeholderStyle:'font-size:17px;',
	  styles:{
	  	borderColor: '#999'
	  },
	  keyword:'',
	  where:'',
	  selectedIndexs:[],//选中
	  
	  value: 1,
	  range: ["默认","物料编码段"],
	  right_options: [{
			text: '明细',
			style: {
				backgroundColor: '#18bc9c'
			}
	  }],
	  user:uni.getStorageSync('user')
    }
  },
  onNavigationBarButtonTap(e) {
  		if(e.type=='menu'){
  			//弹窗
  			this.$refs.popup.open()
  		}
  },
  onPullDownRefresh() {
  	this.getlist()
  	uni.stopPullDownRefresh();
  },
  methods: {
    // 多选
	selectionChange(e) {
		this.selectedIndexs = e.detail.index
	},
	longPressDelete(index){
		//长按 删除
		this.selectedIndexs = []
		this.selectedIndexs.push(index)
		this.toDelete()
	},
	toDelete() {
		let flag = this.checkData('delete')
		if(flag){
			let _this = this;
			uni.showModal({
			    title: '确定要删除记录？',
			    success: function (res) {
			        if (res.confirm) {
						//删除本地记录
						_this.toDealData('delete')
					}
			    }
			});
		}
	},
	checkData(way='update'){
		//验证数据
		let _this = this
		let flag = true
		if(this.selectedIndexs.length>1){
			this.$Api.msg("请选择单条记录");
			return 
		}
		
		for(let i in this.selectedIndexs){
			let key = this.selectedIndexs[i]
			
			if(this.card_arr[key].syn_status==1){
				 this.$Api.msg("存在已同步记录，无法操作")
				 this.$refs.table.clearSelection()
				 return false
			}
			
			if(way=='update'){
				if(this.card_arr[key].status==1){
					 this.$Api.msg("该调拨记录已确认，请勿重复操作")
					 this.$refs.table.clearSelection()
					 return false
				}
				
				if(this.card_arr[key].totalnum == 0){
					 this.$Api.msg("调拨明细不能为空，请核实")
					 this.$refs.table.clearSelection()
					 return false
				}
			}
		}
		return flag
	},
	async toOk(){
		await this.checkData('update');
		let _this = this
		if(this.selectedIndexs.length>0){
			uni.showModal({
				title: '确认要完成调拨单？',
				success: function (res) {
					if(res.confirm){
						_this.toDealData('update')
					}
				},
			})
		}
	},
	async toDealData(way){
		//处理数据，编辑、删除本地记录
		uni.showLoading({
			mask:true
		})
		
		await this.selectedIndexs.forEach(key=>{
			if(way == 'update'){
				this.$Db.updateSqlData('allot',{status:1},'id',this.card_arr[key].id).then(res=>{
					this.toSyn(this.card_arr[key]).catch(err=>{
						this.$Api.msg(err)
					})
				})
			}else if(way == 'delete'){
				//删除表头
				this.$Db.deleteTableData('allot','id',this.card_arr[key].id).catch(err=>{
					this.$Api.msg(err)
				})
				//删除表体
				this.$Db.deleteTableData('allot_item','FBillNo',this.card_arr[key].FBillNo).catch(err=>{
					this.$Api.msg(err)
				})
				
				uni.hideLoading()
				this.$Api.msg('操作成功','success')
				this.search()
			}
		})
		await this.$refs.table.clearSelection()
	},
    selectes(item,flag) {
      if (item == '') return
	  if(flag == 'detail'){
		  uni.showLoading({
		  	mask:true
		  })
		  uni.navigateTo({
		  	url:'/pages/allot/listitem',
		  		delta:1,
		  		success() {
					uni.hideLoading()
		  			uni.$emit("getAllot", item)
		  		}
		  })
	  }else{
		  if(item.status==1){
			  this.$Api.msg('该调拨记录已完成，无法再操作')
			  return 
		  }else{
			  uni.showLoading({
			  	mask:true
			  })
			  uni.navigateTo({
			  	url:'/pages/allot/toscan',
			  		delta:1,
			  		success() {
						uni.hideLoading()
			  			uni.$emit("getAllot", item)
			  		}
			  })
		  }
	  }
    },
	toUnSyn(){
		//撤销同步，针对同步失败的单据
		let _this = this;
		if(!this.selectedIndexs.length||this.selectedIndexs.length>1){
			this.$Api.msg("请选择单条记录进行撤销");
			return 
		}
		let bill = this.card_arr[this.selectedIndexs[0]]
		// if(!bill.syn_status){
		// 	this.$Api.msg("该记录未同步,无法撤销");
		// 	return
		// }
		uni.showModal({
		    title: '确定要撤销同步记录？',
		    //content: '确定要删除记录？',
		    success: function (res) {
		        if (res.confirm) {
					_this.$Db.unSynData('allotbill',bill.FBillNo).then(res=>{
						_this.$Api.msg('撤销成功','success')
						setTimeout(()=>{
							_this.search()
						},1000)
					}).catch(err=>{
						_this.$Api.msg(err)
					})
				}
			},
		})
	},
	// 搜索
	search() {
		this.currentPage = 1;
		this.getlist();
	},
    //获取列表
    async getlist() {
		uni.showLoading();
		this.where = "userid = '"+this.user.userid+"'"
		
		if(this.keyword!=''){
			this.where = "FBillNo like '%"+this.keyword+"%' or invStart like '%"+this.keyword+"%' or invEnd like '%"+this.keyword+"%' or remark like '%"+this.keyword+"%' or FDate like '%"+this.keyword+"%'"
		}
		
		await this.$Db.queryCount('allot',this.where).then(res => {
			this.total = res[0].num;//获得总页数
		})
		
		await this.$Db.queryDataList('allot',this.currentPage,this.pageSize,this.where,'FBillNo','desc').then(res => {
			this.card_arr = res
		}).catch(err=>{
			this.$Api.msg(err)
		})
		
		uni.hideLoading();
    },
	toSyn(bill){
		//回传数据
		let _this = this;
		this.$Db.backSynData('allotbill',bill,16).then(res=>{
			this.$Api.msg('同步成功','success')
			setTimeout(()=>{
				_this.getlist()
			},1000)
		}).catch(err=>{
			this.$Db.unSynData('allotbill',bill.FBillNo)//失败撤销
			this.$Api.msg(err)
			this.$Db.addlog('同步调拨',err)
		})
	},
    change(e) {
      this.currentPage = e.current
      this.getlist()
    }
  },
  onShow() {
	  this.getlist()//才能更新总数
  },
  onLoad(e) {
	  this.$Func.setBarTitle('调拨列表')
  }
}
</script>
<style lang="scss">
</style>